package com.serkol.ams;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.serkol.ams.entity.Users;
import com.serkol.ams.service.UsersService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpQrcodeService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@EnableCaching // 开启缓存的主键
@SpringBootApplication
// @MapperScan("com.serkol.ams.mapper")
@ComponentScan("com.serkol")
@EnableAsync
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableTransactionManagement
@CrossOrigin
@Controller
public class AmsApplication {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private UsersService usersService;
    @Value("${wx.pay.notifyPath}")
    private String notifyPath;
    @Value("${spring.base-url}")
    private String baseUrl;

    @Value("${wx.mp.configs[0].appId}")
    private String appId;

    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        SpringApplication.run(AmsApplication.class, args);
    }

    @GetMapping(value = { "index", "/" })
    public String index(HttpServletRequest request) {
        String servletPath = request.getServletPath();
        System.out.println(servletPath);
        System.out.println(request.getContextPath());
        System.out.println(request.getRequestURI());
        System.out.println(request.getRequestURL());

        return "index.html";
    }

    @GetMapping(" /error")
    public ModelAndView error() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error.html");
        return modelAndView;
    }
    @GetMapping("mplogin/{miniopenid}")
    // @ResponseBody
    public String mplogin(@PathVariable String miniopenid, HttpSession session, HttpServletRequest request)
            throws WxErrorException, UnsupportedEncodingException {
        session.setAttribute("miniopenid", miniopenid);
        System.out.println(miniopenid);
        String servletPath = request.getServletPath();
        System.out.println(servletPath);
        System.out.println(request.getContextPath());
        System.out.println(request.getRequestURI());
        System.out.println(request.getRequestURL());
        System.out.println(request);
        // URLEncoder.encode(miniopenid,"UTF-8")
        String npUrl = baseUrl + "/auth/callback?miniopenid=" + miniopenid;
        String encode = URLEncoder.encode(npUrl, "UTF-8");

        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + encode
                + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

        return "redirect:" + url;
    }

    @GetMapping("/auth/callback")
    public String authCallback(HttpSession session, @RequestParam String code,
            @RequestParam(defaultValue = "0") long shareUserId) {
        try {
            String miniopenid = (String) session.getAttribute("miniopenid");
            // 通过 code 获取 accessToken
            WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);

            String openId = accessToken.getOpenId();
            // 获取用户信息
         //   WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(accessToken, null);

            WxMpUser wxMpUser=    wxMpService.getUserService().userInfo(openId, null);
            Users byLogin = usersService.findByLogin(miniopenid);
            if (byLogin != null) {
                byLogin.setMpSubscribe(wxMpUser.getSubscribe()?1:0);
                byLogin.setMpOpenid(openId);

               // if (byLogin.getNickname() == null) {
                    byLogin.setNickname(wxMpUser.getNickname());
               // }

                if (byLogin.getUnionid() == null) {
                    byLogin.setUnionid(wxMpUser.getUnionId());
                }

                if (byLogin.getAvatar() == null) {
                    byLogin.setAvatar(wxMpUser.getHeadImgUrl());
                }
                usersService.updateById(byLogin);
                // String
                // url="https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=Mzg2MzczNDkzMg==&subscene=0#wechat_redirect";
                String url="";
                if(wxMpUser.getSubscribe()) {
                    url = baseUrl + "/#/mp/suc";
                }else {
                    url = baseUrl + "/#/mp/login/" + byLogin.getId();
                }
              //   url = notifyPath+"/#/mp/suc";
                return "redirect:" + url;
            } else {
                String url = baseUrl+"/#/mp/error";
                return "redirect:"+url; // 授权成功后跳转到成功页面
            }
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

    // MP_verify_2ab3nmIyN9PFHgT1.txt
    @GetMapping("MP_verify_2ab3nmIyN9PFHgT1.txt")
    @ResponseBody
    public String wxVerify() {

        return "2ab3nmIyN9PFHgT1";
    }

    // EQwJdhmR8Q.txt
    @GetMapping("EQwJdhmR8Q.txt")
    @ResponseBody
    public String wxVerify2() {

        return "c3619f3e81202c330672172ab6ae036a";
    }
}
